package com.qf.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author Administrator
 * @version v1.0
 * @date 2022/4/9
 */
public class DataSourceUtils {
    private static DruidDataSource dataSource ;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

    static{
        try {
            Properties properties = new Properties();
            InputStream is = DruidDataSource.class.getClassLoader().getResourceAsStream("db.properties");

            properties.load(is);
             dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            System.out.println("初始化失败"+e.getMessage());
        }
    }

    public static DataSource getDatasource(){
        return dataSource;
    }

    public static Connection getConnection(){
        try {
            Connection connection = threadLocal.get();
            if(connection==null){
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            System.out.println("初始化连接失败"+e.getMessage());
        }
        return null;
    }

    public static void closeAll(ResultSet rs, Statement stat,Connection conn){
        try {
            if(rs!=null){
                rs.close();
            }
            if(stat!=null){
                stat.close();
            }
            if(conn!=null){
                if(conn.getAutoCommit()){
                    conn.close();
                    threadLocal.remove();
                }

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void begin() throws SQLException{
        Connection connection = getConnection();
        if(connection!=null){
            connection.setAutoCommit(false);
        }

    }
    public static void commit() throws SQLException{
        Connection connection = getConnection();
        if(connection!=null){
            connection.commit();
        }

    }
    public static void rollback() throws SQLException{
        Connection connection = getConnection();
        if(connection!=null){
            connection.rollback();
        }

    }
    public static void close() throws SQLException{
        Connection connection = getConnection();
        if(connection!=null){
            connection.close();
            threadLocal.remove();
        }

    }

}
